package com.tanhua.dubbo.api.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLocationApi;
import com.tanhua.dubbo.pojo.UserLocation;
import com.tanhua.dubbo.vo.PageInfo;
import com.tanhua.dubbo.vo.UserLocationVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GeodeticCalculator;
import org.gavaghan.geodesy.GeodeticCurve;
import org.gavaghan.geodesy.GlobalCoordinates;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;

@DubboService(version = "1.0.0")
public class UserLocationApiImpl implements UserLocationApi {

    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;


    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 更新用户地理位置
     *
     * @param userId    用户id
     * @param longitude 经度
     * @param latitude  纬度
     * @param address   地址名称
     * @return
     */
    @Override
    public Boolean updateUserLocation(Long userId, Double longitude, Double latitude, String address) {
        //查询用户的地理位置数据，如果有，就进行更新操作，如果没有，就插入数据

        Query query = Query.query(Criteria.where("userId").is(userId));
        UserLocation userLocation = this.mongoTemplate.findOne(query, UserLocation.class);
        if (null == userLocation) {
            //用户数据不存在，新增操作
            userLocation = new UserLocation();
            userLocation.setLocation(new GeoJsonPoint(longitude, latitude));
            userLocation.setUserId(userId);
            userLocation.setAddress(address);
            userLocation.setCreated(System.currentTimeMillis());
            userLocation.setUpdated(userLocation.getCreated());
            userLocation.setLastUpdated(userLocation.getCreated());
            userLocation.setId(ObjectId.get());

            this.mongoTemplate.save(userLocation);
        } else {
            //更新操作
            Update update = Update.update("location", new GeoJsonPoint(longitude, latitude))
                    .set("address", address)
                    .set("updated", System.currentTimeMillis())
                    .set("lastUpdated", userLocation.getUpdated());
            this.mongoTemplate.updateFirst(query, update, UserLocation.class);
        }

        return true;
    }

    @Override
    public UserLocationVo queryByUserId(Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        return UserLocationVo.format(this.mongoTemplate.findOne(query, UserLocation.class));
    }

    /**
     * 根据位置搜索
     *
     * @param longitude 经度
     * @param latitude  纬度
     * @param distance  距离(米)
     * @param page      页数
     * @param pageSize  页面大小
     */
    @Override
    public PageInfo<UserLocationVo> queryUserFromLocation(Double longitude,
                                                          Double latitude,
                                                          Double distance,
                                                          String gender,
                                                          Integer page,
                                                          Integer pageSize) {
        PageInfo<UserLocationVo> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("location")));
        Distance distanceObj = new Distance(distance / 1000, Metrics.KILOMETERS);
        Circle circle = new Circle(new GeoJsonPoint(longitude, latitude), distanceObj);
        Query query = Query.query(Criteria.where("location")
                .withinSphere(circle))
                .with(pageRequest);
        List<UserLocation> userLocationList = this.mongoTemplate.find(query, UserLocation.class);
        //判断性别是否符合要求,不符合要求的从集合中删除
        List<UserLocation> userLocationList_gender = new ArrayList<>();
        for (UserLocation userLocation : userLocationList) {
            String queryGender = this.userInfoApi.queryGender(userLocation.getUserId());
            if(StrUtil.equals(gender, queryGender)) {
                userLocationList_gender.add(userLocation);
            }
        }
        //若集合为空,直接返回
        if(ObjectUtil.isEmpty(userLocationList_gender)) {
            return pageInfo;
        }
        // TODO 按照距离排序 实现思路：根据坐标进行计算 目标点与 我的点的距离  按照距离进行排序

        //根据坐标距离进行排序
        GlobalCoordinates source = new GlobalCoordinates(longitude, latitude);
        for (int i = 0; i < userLocationList_gender.size(); i++) {
            for (int j = i + 1; j < userLocationList_gender.size(); j++) {
                GlobalCoordinates target1 = new GlobalCoordinates(userLocationList_gender.get(i).getLocation().getX(), userLocationList_gender.get(i).getLocation().getY());
                GlobalCoordinates target2 = new GlobalCoordinates(userLocationList_gender.get(j).getLocation().getX(), userLocationList_gender.get(j).getLocation().getY());

                double meter1 = getDistanceMeter(source, target1, Ellipsoid.Sphere);
                double meter2 = getDistanceMeter(source, target2, Ellipsoid.Sphere);

                if(meter1 > meter2) {
                    UserLocation temp = userLocationList_gender.get(i);
                    userLocationList_gender.set(i, userLocationList_gender.get(j));
                    userLocationList_gender.set(j, temp);
                }
            }
        }

        pageInfo.setRecords(UserLocationVo.formatToList(userLocationList_gender));
        return pageInfo;
    }

    //计算坐标距离
    public static double getDistanceMeter(GlobalCoordinates gpsFrom, GlobalCoordinates gpsTo, Ellipsoid ellipsoid){

        //创建GeodeticCalculator，调用计算方法，传入坐标系、经纬度用于计算距离
        GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(ellipsoid, gpsFrom, gpsTo);

        return geoCurve.getEllipsoidalDistance();
    }
}
